package com.arvin.faceDetect.utils

import android.content.Context
import android.util.Log
import com.arvin.faceDetect.FaceDetectApp
import java.io.File
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import java.util.concurrent.ConcurrentHashMap

object LogUtils {
    private const val TAG = "FaceDetect"
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    private val timeFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault())
    private val fileWriters = ConcurrentHashMap<String, FileWriter>()

    fun init(context: Context) {
        val logDir = File(context.filesDir, "logs")
        if (!logDir.exists()) {
            logDir.mkdirs()
        }

        // 清理过期日志
        cleanExpiredLogs(context, logDir)
    }

    fun d(tag: String, message: String) {
        log("DEBUG", tag, message)
    }

    fun i(tag: String, message: String) {
        log("INFO", tag, message)
    }

    fun w(tag: String, message: String) {
        log("WARN", tag, message)
    }

    fun e(tag: String, message: String, throwable: Throwable? = null) {
        log("ERROR", tag, message + (throwable?.let { "\n${Log.getStackTraceString(it)}" } ?: ""))
    }

    private fun log(level: String, tag: String, message: String) {
        val timestamp = System.currentTimeMillis()
        val dateStr = dateFormat.format(timestamp)
        val timeStr = timeFormat.format(timestamp)

        val logMessage = "$timeStr [$level] $tag: $message\n"

        // 写入日志文件
        try {
            val writer = getLogWriter(dateStr)
            synchronized(writer) {
                writer.write(logMessage)
                writer.flush()
            }
        } catch (e: Exception) {
            Log.e(TAG, "写入日志失败", e)
        }

        // 同时输出到 Logcat
        when (level) {
            "DEBUG" -> Log.d(tag, message)
            "INFO" -> Log.i(tag, message)
            "WARN" -> Log.w(tag, message)
            "ERROR" -> Log.e(tag, message)
        }
    }

    private fun getLogWriter(dateStr: String): FileWriter {
        return fileWriters.computeIfAbsent(dateStr) { date ->
            val logFile = File(getLogDir(), "${date}.log")
            FileWriter(logFile, true)
        }
    }

    private fun cleanExpiredLogs(context: Context, logDir: File) {
        val prefs = context.getSharedPreferences("face_detect_settings", Context.MODE_PRIVATE)
        val retentionDays = prefs.getInt("log_retention_days", 7)
        val calendar = Calendar.getInstance()
        calendar.add(Calendar.DAY_OF_YEAR, -retentionDays)
        val cutoffDate = calendar.timeInMillis

        logDir.listFiles()?.forEach { file ->
            if (file.lastModified() < cutoffDate) {
                file.delete()
            }
        }
    }

    private fun getLogDir(): File {
        return File(FaceDetectApp.instance.filesDir, "logs")
    }

    fun closeLogWriters() {
        fileWriters.values.forEach { writer ->
            try {
                writer.close()
            } catch (e: Exception) {
                Log.e(TAG, "关闭日志写入器失败", e)
            }
        }
        fileWriters.clear()
    }
} 